<template>
  <view class="teacher-select-container">
    <!-- 头部信息 -->
    <view class="header">
      <text class="title">选择老师</text>
      <text class="subtitle">{{ gradeName }} - {{ formattedSubjectNames }}</text>
    </view>
    
    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          type="text" 
          v-model="teacherName" 
          placeholder="搜索老师姓名" 
          confirm-type="search"
          @confirm="loadTeachers"
        />
        <text v-if="teacherName" class="clear-icon" @tap="clearSearch">✕</text>
      </view>
    </view>
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-header">
        <text>筛选条件</text>
        <text class="reset-btn" @tap="resetFilters">重置</text>
      </view>
      
      <scroll-view class="filter-scroll" scroll-x="true">
        <view class="filter-tabs">
          <!-- 学历筛选 -->
          <view class="filter-item">
            <view class="filter-label">学历</view>
            <view class="filter-options">
              <text 
                v-for="(item, index) in educationOptions" 
                :key="'edu-'+index"
                :class="{ active: selectedFilters.education === item.value }"
                @tap="selectFilter('education', item.value)">{{ item.label }}</text>
            </view>
          </view>
          
          <!-- 教龄筛选 -->
          <view class="filter-item">
            <view class="filter-label">教学经验</view>
            <view class="filter-options">
              <text 
                v-for="(item, index) in experienceOptions" 
                :key="'exp-'+index"
                :class="{ active: selectedFilters.experience === item.value }"
                @tap="selectFilter('experience', item.value)">{{ item.label }}</text>
            </view>
          </view>
          
          <!-- 评分筛选 -->
          <view class="filter-item">
            <view class="filter-label">评分</view>
            <view class="filter-options">
              <text 
                v-for="(item, index) in ratingOptions" 
                :key="'rate-'+index"
                :class="{ active: selectedFilters.rating === item.value }"
                @tap="selectFilter('rating', item.value)">{{ item.label }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 切换视图 -->
    <view class="view-toggle">
      <view 
        class="toggle-item" 
        :class="{ active: viewMode === 'list' }"
        @tap="changeViewMode('list')">
        <text class="toggle-icon">📋</text>
        <text>列表</text>
      </view>
      <view 
        class="toggle-item" 
        :class="{ active: viewMode === 'map' }"
        @tap="changeViewMode('map')">
        <text class="toggle-icon">🗺️</text>
        <text>地图</text>
      </view>
    </view>
    
    <!-- 列表视图 -->
    <view v-if="viewMode === 'list'" class="teacher-list">
      <view 
        v-for="teacher in filteredTeachers" 
        :key="teacher.id"
        class="teacher-card"
        @tap="viewTeacherDetail(teacher.id)">
        <view class="teacher-avatar-container">
          <image class="teacher-avatar" :src="teacher.avatar" mode="aspectFill"></image>
          <view class="rating">
            <text>{{ teacher.rating }}分</text>
            <text class="star-icon">★</text>
          </view>
        </view>
        
        <view class="teacher-info">
          <view class="teacher-name-row">
            <text class="teacher-name">{{ teacher.name }}</text>
            <!-- <text class="teacher-education">{{ teacher.certification.education }}</text> -->
          </view>
          
          <view class="teacher-tags">
            <text class="tag">{{ teacher.teachingAge }}年教龄</text>
            <!-- <text class="tag">{{ teacher.hometown }}</text> -->
            <text class="tag">{{  teacher.certification.education}}</text>
          </view>
          
          <view class="teacher-subjects">
            <text class="subject-tag" v-for="(subject, index) in teacher.subjects" :key="index">擅长：{{ subject }}</text>
          </view>
          
          <view class="teacher-feature">
            <!-- <text class="feature-title">教学特色：</text> -->
            <text class="feature-content">{{ teacher.description }}</text>
          </view>
        </view>
     
			
	  </view>
      
      <view v-if="filteredTeachers.length === 0" class="empty-state">
        <image class="empty-icon" src="/static/empty.png"></image>
        <text>没有找到符合条件的老师</text>
        <text class="empty-tip">请尝试修改筛选条件</text>
      </view>
    </view>
    
    <!-- 地图视图 -->
    <view v-if="viewMode === 'map'" class="map-view">
      <map
        id="teacherMap"
        class="teacher-map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :markers="mapMarkers"
        :scale="14"
        :show-location="true"
        @markertap="handleMapMarkerTap"
      ></map>
      
      <!-- 地图控制按钮 -->
      <view class="map-controls">
        <view class="control-btn location-btn" @tap="relocateToCurrentPosition">
          <text class="control-icon">📍</text>
        </view>
        <view class="control-radius">
          <text>{{ searchRadius }}km</text>
          <view class="radius-btns">
            <text @tap="adjustRadius(-1)">-</text>
            <text @tap="adjustRadius(1)">+</text>
          </view>
        </view>
      </view>
      
      <!-- 地图底部浮层（点击教师标记后显示） -->
      <view v-if="selectedMapTeacher" class="map-teacher-info">
        <view class="map-teacher-card">
          <image class="map-teacher-avatar" :src="selectedMapTeacher.avatar" mode="aspectFill"></image>
          <view class="map-teacher-detail">
            <view class="map-teacher-name-row">
              <text class="map-teacher-name">{{ selectedMapTeacher.name }}</text>
              <text class="map-teacher-distance">{{ selectedMapTeacher.distance }}km</text>
            </view>
            <view class="map-teacher-tags">
              <text>{{ selectedMapTeacher.education }}</text>
              <text>{{ selectedMapTeacher.experienceYears }}年教龄</text>
            </view>
            <view class="map-teacher-subjects">
              <text class="subject-tag" v-for="(subject, index) in selectedMapTeacher.subjects" :key="index">{{ subject }}</text>
            </view>
          </view>
        </view>
        <view class="map-teacher-actions">
          <button class="view-detail-btn" @tap="viewTeacherDetail(selectedMapTeacher.id)">查看详情</button>
          <button class="select-teacher-btn" @tap="selectTeacher(selectedMapTeacher.id)">选择</button>
        </view>
      </view>
    </view>
    
    <!-- 底部操作区 -->
    <view class="bottom-bar">
      <button class="back-btn" @tap="goBack">返回</button>
    </view>
  </view>
</template>

<script>
import { teacherApi } from '../../api'

export default {
  data() {
    return {
      gradeId: 0,
      gradeName: '',
      gradeType: '',
      subjectIds: [],
      subjectNames: [],
      
      viewMode: 'list',  // 'list' 或 'map'
      
      // 教师姓名搜索
      teacherName: '',
      
      // 筛选选项
      educationOptions: [
        { label: '全部', value: '' },
        { label: '高中', value: '高中' },
        { label: '本科', value: '本科' },
        { label: '硕士', value: '硕士' },
        { label: '博士', value: '博士' }
      ],
      experienceOptions: [
        { label: '全部', value: '' },
        { label: '1年以下', value: 'below1' },
        { label: '1-3年', value: '1to3' },
        { label: '3-5年', value: '3to5' },
        { label: '5年以上', value: 'above5' }
      ],
      ratingOptions: [
        { label: '全部', value: '' },
        { label: '4.5分以上', value: 'above4.5' },
        { label: '4.0分以上', value: 'above4.0' },
        { label: '3.5分以上', value: 'above3.5' }
      ],
      
      // 已选筛选条件
      selectedFilters: {
        education: '',
        experience: '',
        rating: ''
      },
      
      // 地图相关数据
      mapCenter: {
        latitude: 39.908692,
        longitude: 116.397477
      },
      searchRadius: 5,  // 搜索半径，单位km
      selectedMapTeacher: null,
      
      // 教师数据
      allTeachers: [],
	  
    }
  },
  computed: {
    // 格式化科目名称
    formattedSubjectNames() {
      return this.subjectNames.join('、')
    },
    
    // 根据筛选条件过滤教师
   filteredTeachers() {
      let result = [...this.allTeachers]
      
      // 教育水平筛选
      // if (this.selectedFilters.education) {
      //   result = result.filter(teacher => teacher.educationType === this.selectedFilters.education)
      // }
      
      // // 教学经验筛选
      // if (this.selectedFilters.experience) {
      //   switch (this.selectedFilters.experience) {
      //     case 'below1':
      //       result = result.filter(teacher => teacher.experienceYears < 1)
      //       break
      //     case '1to3':
      //       result = result.filter(teacher => teacher.experienceYears >= 1 && teacher.experienceYears <= 3)
      //       break
      //     case '3to5':
      //       result = result.filter(teacher => teacher.experienceYears > 3 && teacher.experienceYears <= 5)
      //       break
      //     case 'above5':
      //       result = result.filter(teacher => teacher.experienceYears > 5)
      //       break
      //   }
      // }
      
      // 评分筛选
      if (this.selectedFilters.rating) {
        switch (this.selectedFilters.rating) {
          case 'above4.5':
            result = result.filter(teacher => teacher.rating >= 4.5)
            break
          case 'above4.0':
            result = result.filter(teacher => teacher.rating >= 4.0)
            break
          case 'above3.5':
            result = result.filter(teacher => teacher.rating >= 3.5)
            break
        }
      }
      
      return result
    },
   
    // 地图标记点
    mapMarkers() {
      return this.filteredTeachers.map(teacher => ({
        id: teacher.id,
        latitude: teacher.latitude,
        longitude: teacher.longitude,
        title: teacher.name,
        width: 32,
        height: 32,
        callout: {
          content: `${teacher.name}\n${teacher.education.split(' ')[1]}\n${teacher.subjects.join('、')}`,
          color: '#333',
          fontSize: 12,
          borderRadius: 4,
          padding: 8,
          display: 'BYCLICK'
        }
      }))
    }
  },
  onLoad(options) {
    // 获取传递的年级和科目参数
    this.gradeId = parseInt(options.gradeId || 0)
    this.gradeName = options.gradeName || ''
    this.gradeType = options.gradeType || 'primary'
    
    // 解析科目ID和名称
    if (options.subjectIds) {
      this.subjectIds = options.subjectIds.split(',').map(id => parseInt(id))
    }
    
    if (options.subjectNames) {
      this.subjectNames = options.subjectNames.split(',')
    }
    
    uni.setNavigationBarTitle({
      title: '选择教师'
    })
    
    // 获取当前位置
    this.getCurrentLocation()
    
    // 模拟加载教师数据
    this.loadTeachers()
  },
  methods: {
    // 选择筛选条件
    selectFilter(type, value) {
      // 如果已选中，则取消选中
      if (this.selectedFilters[type] === value) {
        this.selectedFilters[type] = ''
      } else {
        this.selectedFilters[type] = value
      }
      
      // 筛选条件改变时，重新加载教师数据
      this.loadTeachers()
    },
    
    // 重置所有筛选条件
    resetFilters() {
      this.selectedFilters = {
        education: '',
        experience: '',
        rating: ''
      }
      
      // 重置后重新加载教师数据
      this.loadTeachers()
    },
    
    // 获取当前位置
    getCurrentLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: res => {
          this.mapCenter.latitude = res.latitude
          this.mapCenter.longitude = res.longitude
        },
        fail: () => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 重新定位到当前位置
    relocateToCurrentPosition() {
      this.getCurrentLocation()
      
      // 重新加载附近教师
      this.loadNearbyTeachers()
    },
    
    // 调整搜索半径
    adjustRadius(change) {
      const newRadius = this.searchRadius + change
      if (newRadius >= 1 && newRadius <= 10) {
        this.searchRadius = newRadius
        
        // 重新加载附近教师
        this.loadNearbyTeachers()
      }
    },
    
    // 加载教师数据
    async loadTeachers() {
      // uni.showLoading({
      //   title: '加载教师数据...'
      // })
		
		// 构建符合后端API的搜索参数
		const searchParams = {
		  page: 1,
		  pageSize: 10,
		  status: 1
		}
		
		// 根据年级设置科目前缀
		let prefix = '';
		if (this.gradeName) {
		  // 使用对象映射替代多个if语句，更简洁清晰
		  const gradeMapping = {
		    '一年级': '小学', '二年级': '小学', '三年级': '小学', '四年级': '小学', '五年级': '小学', '六年级': '小学',
		    '七年级': '初中', '八年级': '初中', '九年级': '初中',
		    '高一': '高中', '高二': '高中', '高三': '高中'
		  };
		  
		  prefix = gradeMapping[this.gradeName] || '';
		}
		
		// 拼接科目字符串，每个科目都加上前缀
		searchParams.subject = this.subjectNames
		  .map(subject => prefix + subject)
		  .join(',');
		
		// 根据筛选条件添加额外参数
		if (this.selectedFilters.experience) {
			switch (this.selectedFilters.experience) {
				case 'below1':
					searchParams.maxTeachingAge = 1
					break
				case '1to3':
					searchParams.minTeachingAge = 1
					searchParams.maxTeachingAge = 3
					break
				case '3to5':
					searchParams.minTeachingAge = 3
					searchParams.maxTeachingAge = 5
					break
				case 'above5':
					searchParams.minTeachingAge = 5
					break
			}
		}
		
		
		
		
		 
		
		// 添加教育程度筛选
		if (this.selectedFilters.education) {
			searchParams.education = this.selectedFilters.education
		}
		
		// 添加教师姓名搜索（如果有）
		if (this.teacherName) {
			searchParams.name = this.teacherName
		}
	
	  const teachersList = await teacherApi.searchTeachers(searchParams);
	  this.allTeachers = teachersList.data.records
	  console.log("所有教师列表", this.allTeachers)
	  
   
      
      setTimeout(() => {
        uni.hideLoading()
        
        // 如果没有匹配的教师，显示提示
        if (this.filteredTeachers.length === 0) {
          uni.showToast({
            title: '未找到符合条件的教师',
            icon: 'none'
          })
        }
      }, 5000)
    },
    
    // 加载附近教师
    loadNearbyTeachers() {
      uni.showLoading({
        title: '搜索附近教师...'
      })
      
      // 实际应用中应调用API获取附近教师数据
      // 这里仅模拟加载过程
      
      setTimeout(() => {
        uni.hideLoading()
        
        // 模拟新数据显示
        uni.showToast({
          title: `已找到${this.mapMarkers.length}位教师`,
          icon: 'success'
        })
      }, 1000)
    },
    
    // 处理地图标记点点击
    handleMapMarkerTap(e) {
      const markerId = e.markerId
      const teacher = this.allTeachers.find(t => t.id === markerId)
      
      if (teacher) {
        this.selectedMapTeacher = teacher
      }
    },
    
    // 查看教师详情
    viewTeacherDetail(teacherId) {
      uni.navigateTo({
        url: `/pages/teacher/detail?id=${teacherId}`
      })
    },
    
    // 选择教师
    selectTeacher(teacherId) {
      const teacher = this.allTeachers.find(t => t.id === teacherId)
      
      if (teacher) {
        uni.navigateTo({
          url: `/pages/booking/detail?teacherId=${teacherId}&gradeId=${this.gradeId}&subjectIds=${this.subjectIds.join(',')}`
        })
      }
    },
    
    // 清除搜索框内容
    clearSearch() {
      this.teacherName = ''
      this.loadTeachers()
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 切换视图模式
    changeViewMode(mode) {
      this.viewMode = mode
      this.loadTeachers() // 切换视图时重新加载数据
    }
  }
}
</script>

<style>
.teacher-select-container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
  padding-bottom: 120rpx; /* 为底部操作栏留出空间 */
}

.header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
}

/* 搜索框样式 */
.search-container {
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  border: 1rpx solid #e0e0e0;
}

.search-icon {
  font-size: 36rpx;
  margin-right: 10rpx;
  color: #999;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  padding: 0;
  height: 60rpx;
  line-height: 60rpx;
}

.clear-icon {
  font-size: 36rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 筛选区域样式 */
.filter-section {
  background-color: #fff;
  padding: 20rpx 0 20rpx 30rpx;
  margin-bottom: 20rpx;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 30rpx;
  margin-bottom: 20rpx;
}

.filter-header text {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.reset-btn {
  font-size: 24rpx;
  color: #1890ff;
  font-weight: normal;
}

.filter-scroll {
  width: 100%;
}

.filter-tabs {
  display: flex;
  width: max-content;
}

.filter-item {
  margin-right: 40rpx;
}

.filter-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.filter-options {
  display: flex;
  gap: 20rpx;
}

.filter-options text {
  font-size: 24rpx;
  color: #333;
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
}

.filter-options text.active {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: bold;
}

/* 视图切换样式 */
.view-toggle {
  display: flex;
  background-color: #fff;
  padding: 15rpx 30rpx;
  margin-bottom: 20rpx;
}

.toggle-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15rpx 0;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
}

.toggle-icon {
  font-size: 32rpx;
  margin-bottom: 6rpx;
}

.toggle-item.active {
  background-color: #f0f8ff;
  color: #1890ff;
}

/* 教师列表样式 */
.teacher-list {
  padding: 0 30rpx;
}

.teacher-card {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  display: flex;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.teacher-avatar-container {
  position: relative;
  margin-right: 20rpx;
}

.teacher-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-right: 20rpx;
    border: 2rpx solid #f5f5f5;
}

.rating {
  position: absolute;
  bottom: 13px;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 22rpx;
  padding: 4rpx 0;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.star-icon {
  color: #ffcf00;
  margin-left: 4rpx;
}

.teacher-info {
  flex: 1;
}

.teacher-name-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.teacher-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.teacher-education {
  font-size: 24rpx;
  color: #1890ff;
}

.teacher-tags {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.tag {
  font-size: 22rpx;
  color: #666;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.teacher-subjects {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.subject-tag {
  font-size: 22rpx;
  color: #ff6b00;
  background-color: #fff2e8;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.teacher-feature {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.feature-title {
  color: #333;
  font-weight: bold;
}

.feature-content {
     /* font-size: 26rpx; */
     color: #999;
     margin-bottom: 20rpx;
     display: -webkit-box;
     -webkit-box-orient: vertical;
     -webkit-line-clamp: 1;
     overflow: hidden;
}

/* 空状态样式 */
.empty-state {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 28rpx;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
  opacity: 0.7;
}

.empty-tip {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #1890ff;
}

/* 地图视图样式 */
.map-view {
  position: relative;
  width: 100%;
  height: calc(100vh - 380rpx);
}

.teacher-map {
  width: 100%;
  height: 100%;
}

.map-controls {
  position: absolute;
  bottom: 30rpx;
  right: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  align-items: flex-end;
}

.control-btn {
  width: 80rpx;
  height: 80rpx;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-icon {
  font-size: 40rpx;
}

.control-radius {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 24rpx;
  color: #333;
}

.radius-btns {
  display: flex;
  gap: 20rpx;
  margin-top: 8rpx;
}

.radius-btns text {
  width: 40rpx;
  height: 40rpx;
  background-color: #f0f0f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.map-teacher-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.map-teacher-card {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.map-teacher-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  background-color: #f0f0f0;
}

.map-teacher-detail {
  flex: 1;
}

.map-teacher-name-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.map-teacher-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.map-teacher-distance {
  font-size: 24rpx;
  color: #ff6b00;
}

.map-teacher-tags {
  display: flex;
  gap: 16rpx;
  margin-bottom: 12rpx;
  font-size: 24rpx;
  color: #666;
}

.map-teacher-actions {
  display: flex;
  gap: 20rpx;
}

.view-detail-btn, .select-teacher-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
}

.view-detail-btn {
  background-color: #f0f0f0;
  color: #333;
}

.select-teacher-btn {
  background-color: #1890ff;
  color: #fff;
}

/* 底部操作栏样式 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn {
  width: 100%;
  background-color: #f0f0f0;
  color: #333;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style> 